package com.example.userprofile

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.SavedStateViewModelFactory
import androidx.lifecycle.ViewModelProvider
//import androidx.lifecycle.observe
import com.example.mydemoapp.R

class UserProfileFragment : Fragment() {
    private  val viewModel : UserProfileViewModel by viewModels(factoryProducer = { SavedStateViewModelFactory(
        this.activity?.application, this)})

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.userprofile_fragment,container,false)
    }

    //observe the data and update the UI
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        //Every time the user profile data is updated, the onChanged() callback is invoked, and the UI is refreshed.
//        val viewModel = UserProfileViewModel.UserProfileViewModelFactory().create(UserProfileViewModel::class.java)
//        val viewModel = ViewModelProvider.AndroidViewModelFactory(activity?.application!!).create(UserProfileViewModel::class.java)
        viewModel.user.observe(viewLifecycleOwner, {
            //update UI
            view.findViewById<TextView>(R.id.liveDataTextView).text = it.id +":"+ it.name +":"+ it.lastName
        })

        view.findViewById<Button>(R.id.updateUserButton).setOnClickListener {
            //update user model
            viewModel.changeUser(User("1@","2","3"))
//            view.findViewById<TextView>(R.id.operationText).text = "Update User#"
        }

        view.findViewById<Button>(R.id.addUserButton).setOnClickListener {
            //update user model
            viewModel.changeUser(User("A","B","C"))
//            view.findViewById<TextView>(R.id.operationText).text = "Add User:"
        }
    }
}